const app = getApp();

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

//字符串转buffer 十六进制
function stringToHexBuffer(data) {
  var typedArray = new Uint8Array(data.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))

  return typedArray.buffer
}

// 字符串转byte
function stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

// home/BleHome.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    IsConnect: false,
    showConnect: false,
    showStartBtn: false,
    devices: [],
    chs: [],
    deviceDatas: [],
    nowDayStepNumber: 14532,
    motionTime: 247,
    startHour: 0,
    startMin: 0
  },

  userInfo:function(){
    wx.navigateTo({
      url: '../useAdmin/useAdmin' 
    })
  },
  realTimeData:function(){
    wx.navigateTo({
      url: '../realTimeData/realTimeData' 
    })
  },
  showData:function(){
    wx.navigateTo({
      url: '../showData/showData' 
    })
  },
  physicalData:function(){
    wx.navigateTo({
      url: '../physicalData/physicalData' 
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // try {
    //   var value = wx.getStorageSync('deviceDatas');
    //   var stepNumber = wx.getStorageSync('stepNumber');
    //   var nowDayStartTime = wx.getStorageSync('nowDayStartTime');
    //   var motionTime = wx.getStorageSync('motionTime');
    //   if (value) {
    //     this.data.deviceDatas = value;
    //     this.data.motionTime = this.data.deviceDatas.length / 2;
    //   }
      // if (stepNumber != null) {
      //   this.data.nowDayStepNumber = stepNumber;
      // }
      // if (motionTime){
      //   this.data.motionTime = motionTime;
      // }
      // if (nowDayStartTime){
      //   this.data.startHour = nowDayStartTime.startHour;
      //   this.data.startMin = nowDayStartTime.startMin;
      // }
    // } catch (e) {
    //   console.log('获取数据异常');
    // }
    this.setData({
      IsConnect:wx.getStorageSync('IsConnect')
    });
  },

  // 同步数据
  upload:function(){
    this.writeBLECharacteristicValue("REQDATA");
  },

  /**
   * 点击连接设备
   */
  connectBtn:function(){
    this.setData({
      showConnect: true
    });
  },

  /**
   * 点击Start
   */
  startBtn:function(){
    let  d= Date.parse(new Date())/1000;
    let  parameter="START"+d;
    console.log('时间戳多少位？必须到秒的'+parameter)
    this.writeBLECharacteristicValue(parameter);
    this.setData({
      showStartBtn: false
    })
  },

  ///////// 蓝牙 //////////
  /**
   * 打开蓝牙适配器
   */
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        } else {
          console.log('onBluetoothAdapterStateChange fail', res)
        }
      }
    })
  },
  /**
   * 获取蓝牙适配器状态
   */
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      },
      fail(res) {
        console.log('getBluetoothAdapterState fail', res)
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
      fail(res) {
        console.log('startBluetoothDevicesDiscovery fail', res)
      }
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  /**
   * 创建连接
   */
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    console.log('连接设备：', ds)
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        console.log('连接成功', res)
        this.setData({
          showConnect: false,
          showStartBtn: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      showConnect: false,
      chs: [],
      canWrite: false,
    })
  },
  /**
   * 连接成功之后解析该设备中的服务
   */
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log('分析服务码', res)
        for (let i = 0; i < res.services.length; i++) {
          // 注：解析过程出现两个service，第二个是以前使用的，所以这里添加判断
          if (res.services[i].uuid.indexOf("6E400001") != -1) {
            if (res.services[i].isPrimary) {
              this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
              return
            }
          }
        }
      },
      fail(res) {
        console.log('获取服务码错误：', res)
      }
    });
  },
  /**
   * 获取到我们需要的服务之后解析服务中的write和notify服务
   */
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    var that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            // this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    });
    // 操作之前先监听，保证第一时间获取数据，即先注册notify服务，随时监听着
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      console.log(characteristic.value);

      // 接受到end说明 请求结束
      if (characteristic.value.byteLength != 16){
        
        that.setData({
          nowDayStepNumber: that.data.nowDayStepNumber,
          motionTime: that.data.motionTime
        })

        try {
          var date = new Date();
          var dayKey = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
          wx.setStorageSync(dayKey, that.data.deviceDatas);
          wx.setStorageSync('stepNumber', that.data.nowDayStepNumber);
          wx.setStorageSync('motionTime', that.data.motionTime);
        } catch (e) {
          console.log('数据保存失败');
        }

        wx.hideLoading();
        wx.navigateTo({
          url: '../showData/showData'
        })
        return;
      }

      // 一条数据 添加到这一秒数组中
      var stepNumber = new Int16Array(characteristic.value.slice(0, 2));// 步数
      var phyEnergy = new Float32Array(characteristic.value.slice(2, 6));// 体能
      var expForce = new Float32Array(characteristic.value.slice(6, 10));// 爆发力
      var dataTime = new Int32Array(characteristic.value.slice(10, 14));// 时间戳
      var workState = new Int32Array(characteristic.value.slice(14, 15));// 工作状态
      var handPower = new Int32Array(characteristic.value.slice(15, 16));// 电量

      // var itemNumber = new Int32Array(characteristic.value.slice(15, 16));// 包号

      var itemData = {
        stepNumber: stepNumber[0],
        phyEnergy: phyEnergy[0],
        expForce: expForce[0],
        dataTime: dataTime[0],
        workState: workState[0],
        handPower: handPower[0],
        // itemNumber: itemNumber[0],
        startHour: that.data.startHour,
        startMin: that.data.startMin
      }
      console.log("获取数据，即先注册notify"+itemData);
      that.data.deviceDatas.push(itemData);

      that.data.nowDayStepNumber += parseInt(itemData.stepNumber);
      that.data.motionTime += 0.5;
    });
  },
  /**
   * 向设备写入命令
   */
  writeBLECharacteristicValue(command) {
    var that = this;
    /*
      对应命令转为16进制的形式
      START   = [83, 84, 65, 82, 84]
      STOP    = [83, 84, 79, 80]
      REQDATA = [82, 69, 81, 68, 65, 84, 65]
    */
    var buffer = stringToBytes(command)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
      success: function (res) {
        if (command === "REQDATA"){
          wx.showLoading({
            title: '正在同步数据...',
          });
        }else if(command === "START"){

          // 注：发送start需要记录发送的小时、分钟，并保存到缓存中
          var date = new Date();
          that.data.startHour = date.getHours();
          that.data.startMin = date.getMinutes();
          var startTime = {
            startHour: that.data.startHour,
            startMin: that.data.startMin
          }
          try {
            wx.setStorageSync('nowDayStartTime', startTime);
          } catch (e) {
            console.log('数据保存失败');
          }
        }
        console.log("发送成功", res)
      },
      fail(res) {
        console.log("发送失败", res)
      }
    })
  },
  closeBluetoothAdapter() {
    this.setData({
      showConnect: false
    });
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  closeBtn() {
    wx.closeBluetoothAdapter()
    this.setData({
      IsConnect: false,
    })
    this._discoveryStarted = false
  },
})